package com.luoxc.aop;

import com.alibaba.fastjson.JSONObject;
import com.luoxc.mapper.LogMapper;
import com.luoxc.pojo.OperateLog;
import com.luoxc.utils.JwtHandle;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

@Component
@Aspect
@Slf4j
public class LogAspect {
    @Autowired
    private LogMapper logMapper;
    @Autowired
    private HttpServletRequest httpServletRequest;
@Around("execution(* com.luoxc.mapper.*.*(..)) && !execution(* com.luoxc.mapper.EmpMapper.getUsernameAndPassword(..)) && " +
        "!execution(* com.luoxc.mapper.LogMapper.add(..))")
    private Object log(ProceedingJoinPoint joinPoint) throws Throwable {
        String token = httpServletRequest.getHeader("token");
        Claims parseJwt = JwtHandle.parseJwt(token);

        // 获取操作人员id
        int userId = (int)parseJwt.get("userId");
        log.info("userID:" + userId);
        // 获取操作时间
        LocalDateTime now = LocalDateTime.now();
        // 获取操作类名
        String name = joinPoint.getTarget().getClass().getName();
        // 获取方法名
        String methodName = joinPoint.getSignature().getName();
        // 获取方法参数
        String args = Arrays.toString(joinPoint.getArgs());

        long begin = System.currentTimeMillis(); // 开始时间
        // 获取返回值
        Object proceed = joinPoint.proceed();
        String res = JSONObject.toJSONString(proceed);

        long end = System.currentTimeMillis(); // 结束时间
        // 获取运行时间
        long cosTime =end - begin;
        OperateLog operateLog = new OperateLog(userId,now,name,methodName,args,res,cosTime);
        logMapper.add(operateLog);

        return proceed;
    }
}
